<?php
// 应用公共文件

if (!function_exists('encrypt')) {
    /**
     * 加密
     * @param $data
     * @param string $key
     * @return string
     */
    function encrypt($data, $key = '112233'): string
    {
        $char = '';
        $str  = '';
        $key  = md5($key);
        $x    = 0;
        $len  = strlen($data);
        $l    = strlen($key);
        for ($i = 0; $i < $len; $i++) {
            if ($x == $l) {
                $x = 0;
            }
            $char .= $key[$x];
            $x++;
        }
        for ($i = 0; $i < $len; $i++) {
            $str .= chr(ord($data[$i]) + (ord($char[$i])) % 256);
        }
        return base64_encode($str);
    }
}

if (!function_exists('decrypt')) {
    /**
     * 解密
     * @param $data
     * @param string $key
     * @return string
     */
    function decrypt($data, $key = '112233'): string
    {
        $char = '';
        $str  = '';
        $key  = md5($key);
        $x    = 0;
        $data = base64_decode($data);
        $len  = strlen($data);
        $l    = strlen($key);
        for ($i = 0; $i < $len; $i++) {
            if ($x == $l) {
                $x = 0;
            }
            $char .= substr($key, $x, 1);
            $x++;
        }
        for ($i = 0; $i < $len; $i++) {
            if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
                $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
            } else {
                $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
            }
        }
        return $str;
    }
}


if (!function_exists('now')) {
    /**
     * 当期时间
     * @param string $type
     * @return false|string
     */
    function now($type = "Y-m-d H:i:s")
    {
        return date($type, time());
    }
}


if (!function_exists('msg_success')) {
    function msg_success($msg = '操作成功', $data = []): \think\response\Json
    {
        return json([
            'msg'    => $msg,
            'data'   => $data,
            'status' => true,
        ]);
    }
}
if (!function_exists('msg_error')) {
    function msg_error($msg = '操作失败', $data = []): \think\response\Json
    {
        $msg_power = get_msg();
        if ($msg_power) {
            $msg = $msg_power;
        }
        return json([
            'msg'    => $msg,
            'data'   => $data,
            'status' => false,
        ]);
    }
}
if (!function_exists('arr_success')) {
    function arr_success($msg = '操作成功', $data = []): array
    {
        return [
            'msg'    => $msg,
            'data'   => $data,
            'status' => true,
        ];
    }
}
if (!function_exists('arr_error')) {
    function arr_error($msg = '操作失败', $data = []): array
    {
        return [
            'msg'    => $msg,
            'data'   => $data,
            'status' => false,
        ];
    }
}
if (!function_exists('lay_data')) {
    function lay_data($paginate, $msg = false): \think\response\Json
    {
        if (!is_array($paginate)) {
            $paginate = $paginate->toArray();
        }
        return json([
            'code'  => $msg ? 500 : 0,
            'msg'   => $msg ?: 'Success',
            'count' => $msg ? 0 : (isset($paginate['total']) ? $paginate['total'] : count($paginate)),
            'data'  => $msg ? [] : (isset($paginate['data']) ? $paginate['data'] : $paginate),
        ]);
    }
}
if (!function_exists('return_true_or_false')) {
    function return_true_or_false($info, $msg = '操作成功')
    {
        if ($info) {
            return msg_success($msg);
        } else {
            return msg_error();
        }
    }
}
if (!function_exists('get_msg')) {
    function get_msg()
    {
        $msg = session('power');
        if (!$msg) {
            return false;
        } else {
            session('power', false);
            return $msg;
        }
    }
}
if (!function_exists('power')) {
    function power($name, $display_name = false, $type = false): bool
    {
        try {
            $per = \app\admin\model\Permission::where('name', $name)->find();
            if (!$per) {
                \app\admin\model\Permission::create([
                    'name'         => $name,
                    'display_name' => ($display_name ?: $name),
                    'type'         => $type ?: ''
                ]);
            }

            $user = auth();
            if (!$user->role) {
                return false;
            }
            if ($user->username == 'admin') {
                return true;
            }
            $role        = $user->role;
            $permissions = $role->permissions;
            if (!$role->permissions) {
                return false;
            }
            $perm_names = array_column($permissions->toArray(), 'name');

            if (!in_array($name, $perm_names)) {
                return false;
            }

            if ($user) {
                return $user['frozen'] == 0;
            } else {
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }
    }
}
if (!function_exists('get_plugin_nav')) {
    function get_plugin_nav()
    {
        $uri = app()->getRootPath() . "/app/plugin/config/";
        $arr = folder_list($uri);

        $nav = [];
        foreach ($arr as $k => $item) {
            $file   = file_get_contents($item['name']);
            $config = json_decode($file, true);
            $Plugin = \app\admin\model\Plugin::where('name', $config['name'])->find();
            if ($Plugin && $Plugin->frozen == '启用') {
                $json_nav  = $config['nav'];
                if(isset($json_nav['name'])){
                    if(power($json_nav['power'],$json_nav['name'],'nav')){
                        $nav[] = $json_nav;
                    }
                }else{
                    foreach ($json_nav as $key=>$value){
                        if(power($value[0]['power'],$key,'nav')) {
                            $arr_nav = [
                                'name'  => $key,
                                'power' => $value[0]['power'],
                                'icon'  => $value[0]['icon'],
                                'child' => []
                            ];
                            foreach ($value as $it) {
                                if (isset($it['name'])) {
                                    if(power($it['power'],$it['name'],'nav')) {
                                        $arr_nav['child'][] = [
                                            'name'  => $it['name'],
                                            'power' => $it['power'],
                                            'url'   => '/'.$config['name'].'/'.$it['url'],
                                            'child' => []
                                        ];
                                    }
                                }
                            }
                            $nav[] = $arr_nav;
                        }
                    }
                }

            }
        }
        return $nav;
    }
}
if (!function_exists('deldir')) {
    function deldir($dir) {
        //先删除目录下的文件：
        $dh=opendir($dir);
        while ($file=readdir($dh)) {
            if($file!="." && $file!="..") {
                $fullpath=$dir."/".$file;
                if(!is_dir($fullpath)) {
                    unlink($fullpath);
                } else {
                    deldir($fullpath);
                }
            }
        }

        closedir($dh);
        //删除当前文件夹：
        if(rmdir($dir)) {
            return true;
        } else {
            return false;
        }
    }
}
if (!function_exists('delFile')) {
    function delFile($path)
    {
        $url = iconv('utf-8', 'gbk', $path);
        if (PATH_SEPARATOR == ':') { //linux
            unlink($path);
        } else {  //Windows
            unlink($url);
        }
    }
}
if (!function_exists('folder_list')) {
    function folder_list($dir): array
    {
        $dir     .= substr($dir, -1) == '/' ? '' : '/';
        $dirInfo = array();
        foreach (glob($dir . '*') as $v) {
            $arr          = array();
            $arr['name']  = $v;
            $arr['child'] = (is_dir($v)) ? folder_list($v) : array();
            $dirInfo[]    = $arr;
        }
        return $dirInfo;
    }
}
if (!function_exists('auth')) {
    function auth()
    {
        $session = session('token');
        if (empty($session)) {
            return false;
        } else {
            try {
                $username = decrypt($session);
                return \app\admin\model\User::where('name', $username)->find();
            } catch (\Exception $e) {
                return false;
            }
        }
    }
}